<template>
    <div class="min-h-screen bg-gray-50">
        <!-- 头部导航 -->
        <div class="bg-white shadow-sm border-b">
            <div class="max-w-6xl mx-auto px-6 py-4">
                <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-4">
                        <el-button type="text" @click="goBack" class="!text-gray-600 hover:!text-blue-600">
                            <el-icon class="mr-1">
                                <ArrowLeft />
                            </el-icon>
                            返回
                        </el-button>
                        <div class="w-px h-6 bg-gray-300"></div>
                        <h1 class="text-xl font-semibold text-gray-800">3D模型评估报告</h1>
                    </div>
                    <div class="flex items-center space-x-3">
                        <el-button type="primary" @click="downloadReport">
                            <el-icon class="mr-1">
                                <Download />
                            </el-icon>
                            下载报告
                        </el-button>
                        <el-button @click="shareReport">
                            <el-icon class="mr-1">
                                <Share />
                            </el-icon>
                            分享
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="flex items-center justify-center py-20">
            
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="max-w-6xl mx-auto px-6 py-20">
            <el-result icon="error" title="加载失败" :sub-title="error">
                <template #extra>
                    <el-button type="primary" @click="loadReport">重新加载</el-button>
                </template>
            </el-result>
        </div>

        <!-- 报告内容 -->
        <div v-else-if="reportData" class="max-w-6xl mx-auto px-6 py-8">
            <div class="grid grid-cols-12 gap-8">
                <!-- 主要内容区域 -->
                <div class="col-span-8">
                    <!-- 报告头部信息 -->
                    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
                        <div class="flex items-start justify-between">
                            <div class="flex-1">
                                <h2 class="text-2xl font-bold text-gray-800 mb-2">
                                    {{ reportData.title }}
                                </h2>
                                <div class="flex items-center space-x-4 text-sm text-gray-600">
                                    <span>
                                        <el-icon class="mr-1">
                                            <Calendar />
                                        </el-icon>
                                        {{ formatDate(reportData.create_time) }}
                                    </span>
                                    <span>
                                        <el-icon class="mr-1">
                                            <User />
                                        </el-icon>
                                        用户ID: {{ reportData.user_id }}
                                    </span>
                                    <span v-if="reportData.overall_score">
                                        <el-icon class="mr-1">
                                            <Star />
                                        </el-icon>
                                        评分: {{ reportData.overall_score }}/10
                                    </span>
                                </div>
                            </div>
                            <!-- 状态标签 -->
                            <el-tag :type="reportData.read_status ? 'success' : 'info'" size="small">
                                {{ reportData.read_status ? '已读' : '未读' }}
                            </el-tag>
                        </div>
                    </div>

                    <!-- Markdown 报告内容 -->
                    <div class="bg-white rounded-lg shadow-sm p-6">
                        <div class="prose prose-lg max-w-none">
                            <div v-html="renderedMarkdown" class="markdown-content"></div>
                        </div>
                    </div>
                </div>

                <!-- 侧边栏 -->
                <div class="col-span-4">
                    <!-- 3D模型预览 -->
                    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
                        <h3 class="text-lg font-semibold text-gray-800 mb-4">模型预览</h3>
                        <div class="aspect-square bg-gray-100 rounded-lg mb-4 relative overflow-hidden">
                            <img v-if="reportData.screenshot" :src="reportData.screenshot" alt="模型预览"
                                class="w-full h-full object-cover" />
                            <div v-else class="flex items-center justify-center h-full text-gray-400">
                                <el-icon size="48">
                                    <Picture />
                                </el-icon>
                            </div>
                        </div>
                        <el-button type="primary" class="w-full" @click="viewModel">
                            <el-icon class="mr-1">
                                <View />
                            </el-icon>
                            查看3D模型
                        </el-button>
                    </div>

                    <!-- 快速信息 -->
                    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
                        <h3 class="text-lg font-semibold text-gray-800 mb-4">快速信息</h3>
                        <div class="space-y-3">
                            <div class="flex justify-between items-center">
                                <span class="text-gray-600">模型URL:</span>
                                <el-button type="text" size="small" @click="copyModelUrl" class="!p-0">
                                    复制链接
                                </el-button>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-gray-600">报告生成:</span>
                                <span class="text-sm">{{ formatDate(reportData.create_time) }}</span>
                            </div>
                            <div v-if="reportData.overall_score" class="flex justify-between items-center">
                                <span class="text-gray-600">整体评分:</span>
                                <div class="flex items-center space-x-1">
                                    <el-rate v-model="normalizedScore" disabled show-score text-color="#ff9900"
                                        score-template="{value}" />
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 操作面板 -->
                    <div class="bg-white rounded-lg shadow-sm p-6">
                        <h3 class="text-lg font-semibold text-gray-800 mb-4">操作</h3>
                        <div class="space-y-3">
                            <el-button class="w-full" @click="downloadReport">
                                <el-icon class="mr-1">
                                    <Download />
                                </el-icon>
                                下载PDF报告
                            </el-button>
                            <el-button class="w-full" @click="exportMarkdown">
                                <el-icon class="mr-1">
                                    <Document />
                                </el-icon>
                                导出Markdown
                            </el-button>
                            <el-button class="w-full" @click="shareReport">
                                <el-icon class="mr-1">
                                    <Share />
                                </el-icon>
                                分享报告
                            </el-button>
                            <el-button class="w-full" type="danger" plain @click="deleteReport">
                                <el-icon class="mr-1">
                                    <Delete />
                                </el-icon>
                                删除报告
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    ArrowLeft,
    Download,
    Share,
    Calendar,
    User,
    Star,
    Picture,
    View,
    Document,
    Delete
} from '@element-plus/icons-vue'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import request from '@/util/request'
import { useNotificationStore } from '@/store/notification'

const route = useRoute()
const router = useRouter()
const notificationStore = useNotificationStore()

// 响应式数据
const loading = ref(true)
const error = ref('')
const reportData = ref(null)

// 计算属性
const reportId = computed(() => route.params.id)

const normalizedScore = computed(() => {
    if (!reportData.value?.overall_score) return 0
    // 将10分制转换为5分制
    return (reportData.value.overall_score / 10) * 5
})

const renderedMarkdown = computed(() => {
    if (!reportData.value?.markdown_report) return ''

    // 配置 marked 选项
    marked.setOptions({
        highlight: function (code, lang) {
            // 简单的代码高亮处理
            return `<pre><code class="language-${lang}">${code}</code></pre>`
        },
        breaks: true,
        gfm: true
    })

    // 渲染 Markdown 并清理 HTML
    const rawHtml = marked(reportData.value.markdown_report)
    return DOMPurify.sanitize(rawHtml)
})

// 方法
const loadReport = async () => {
    try {
        loading.value = true
        error.value = ''

        const response = await request.get(`/backcode/model/markReportAsRead/${reportId.value}`)
        reportData.value = response
    } catch (err) {
        error.value = err.message || '加载报告时发生错误'
        console.error('加载报告失败:', err)
    } finally {
        loading.value = false
    }
}

const markAsRead = async () => {
    try {
        await request.post(`/api/v2/evaluation/reports/${reportId.value}/read`)

        // 更新本地数据
        if (reportData.value) {
            reportData.value.read_status = 1
        }

        // 更新通知 store 中的状态
        const notification = notificationStore.notifications.find(
            n => n.reportId == reportId.value
        )
        if (notification) {
            notificationStore.markAsRead(notification.id)
        }
    } catch (err) {
        console.error('标记已读失败:', err)
    }
}

const goBack = () => {
    if (window.history.length > 1) {
        router.go(-1)
    } else {
        router.push('/')
    }
}

const viewModel = () => {
    if (reportData.value?.model_3d_url) {
        window.open(reportData.value.model_3d_url, '_blank')
    } else {
        ElMessage.warning('模型链接不可用')
    }
}

const copyModelUrl = async () => {
    if (!reportData.value?.model_3d_url) {
        ElMessage.warning('模型链接不可用')
        return
    }

    try {
        await navigator.clipboard.writeText(reportData.value.model_3d_url)
        ElMessage.success('模型链接已复制到剪贴板')
    } catch (err) {
        ElMessage.error('复制失败')
    }
}

const downloadReport = () => {
    if (!reportData.value) return

    // 创建 PDF 下载 - 这里可以集成 PDF 生成库
    ElMessage.info('PDF下载功能开发中...')
}

const exportMarkdown = () => {
    if (!reportData.value?.markdown_report) return

    const blob = new Blob([reportData.value.markdown_report], {
        type: 'text/markdown;charset=utf-8'
    })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${reportData.value.title || '评估报告'}.md`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('Markdown文件已导出')
}

const shareReport = async () => {
    const url = window.location.href

    if (navigator.share) {
        try {
            await navigator.share({
                title: reportData.value?.title || '3D模型评估报告',
                text: '查看这个3D模型评估报告',
                url: url
            })
        } catch (err) {
            if (err.name !== 'AbortError') {
                copyToClipboard(url)
            }
        }
    } else {
        copyToClipboard(url)
    }
}

const copyToClipboard = async (text) => {
    try {
        await navigator.clipboard.writeText(text)
        ElMessage.success('链接已复制到剪贴板')
    } catch (err) {
        ElMessage.error('分享失败')
    }
}

const deleteReport = async () => {
    try {
        await ElMessageBox.confirm(
            '确定要删除这个评估报告吗？此操作不可恢复。',
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        // 这里应该调用删除 API
        ElMessage.info('删除功能开发中...')

    } catch (err) {
        // 用户取消删除
    }
}

const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    })
}

// 生命周期
onMounted(() => {
    loadReport()
})

// 设置页面标题
onMounted(() => {
    if (reportData.value?.title) {
        document.title = `${reportData.value.title} - 3D模型评估报告`
    }
})

onUnmounted(() => {
    // 恢复默认标题
    document.title = '3D-Generator'
})
</script>

<style scoped lang="less">
.custom-spinner {
    display: flex;
    align-items: center;
    justify-content: center;

    .spinner-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: #409eff;
        margin: 0 3px;
        animation: spinner-bounce 1.4s ease-in-out infinite both;

        &:nth-child(1) {
            animation-delay: -0.32s;
        }

        &:nth-child(2) {
            animation-delay: -0.16s;
        }
    }
}

@keyframes spinner-bounce {

    0%,
    80%,
    100% {
        transform: scale(0);
    }

    40% {
        transform: scale(1);
    }
}

/* Markdown 内容样式 */
.markdown-content {
    line-height: 1.7;

    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
        margin-top: 2rem;
        margin-bottom: 1rem;
        font-weight: 600;
        line-height: 1.25;

        &:first-child {
            margin-top: 0;
        }
    }

    h1 {
        font-size: 2rem;
    }

    h2 {
        font-size: 1.5rem;
    }

    h3 {
        font-size: 1.25rem;
    }

    h4 {
        font-size: 1.125rem;
    }

    p {
        margin-bottom: 1rem;
    }

    ul,
    ol {
        margin: 1rem 0;
        padding-left: 2rem;

        li {
            margin-bottom: 0.5rem;
        }
    }

    blockquote {
        margin: 1.5rem 0;
        padding: 1rem 1.5rem;
        border-left: 4px solid #3b82f6;
        background-color: #f8faff;
        border-radius: 0 4px 4px 0;

        p:last-child {
            margin-bottom: 0;
        }
    }

    code {
        padding: 0.2rem 0.4rem;
        background-color: #f3f4f6;
        border-radius: 3px;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
        font-size: 0.875rem;
    }

    pre {
        margin: 1.5rem 0;
        padding: 1rem;
        background-color: #1f2937;
        border-radius: 6px;
        overflow-x: auto;

        code {
            padding: 0;
            background-color: transparent;
            color: #f9fafb;
        }
    }

    table {
        width: 100%;
        margin: 1.5rem 0;
        border-collapse: collapse;

        th,
        td {
            padding: 0.75rem;
            text-align: left;
            border-bottom: 1px solid #e5e7eb;
        }

        th {
            font-weight: 600;
            background-color: #f9fafb;
        }
    }

    hr {
        margin: 2rem 0;
        border: none;
        border-top: 1px solid #e5e7eb;
    }

    img {
        max-width: 100%;
        height: auto;
        border-radius: 4px;
        margin: 1rem 0;
    }

    strong {
        font-weight: 600;
    }

    em {
        font-style: italic;
    }
}
</style>

